/**
 * @author lteng
 * @time 2022-06-19 11:15:20 
 */

package liteng.study.cn.stuscore.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import liteng.study.cn.stuscore.entity.User;
import liteng.study.cn.stuscore.service.UserService;
import liteng.study.cn.stuscore.service.impl.UserServiceImpl;

/**
 * 个人信息
 */
@WebServlet("/info")
public class InfoServlet extends HttpServlet {
	UserService userService = new UserServiceImpl();
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		String action = request.getParameter("action");
		
		if (action.equals("updInfo")) {
			updInfo(request,response);
		}else if (action.equals("updPwd")) {
			updPwd(request,response);
		}
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void updPwd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// TODO Auto-generated method stub
		String oldPwd = request.getParameter("oldPwd");
		String newPwd = request.getParameter("newPwd");
		System.out.println(oldPwd+newPwd);
		User user = (User) request.getSession().getAttribute("user");
		
		if (oldPwd.equals(user.getPassWord())) {
			user.setPassWord(newPwd);
			userService.update(user);
			
			request.getSession().setAttribute("user", user);
			System.out.println(user+"14444444444444444444");
			
			response.sendRedirect("/stuscore/");
		}else {
			request.setAttribute("error", "原始密码错误");
			request.getRequestDispatcher("/pages/info/pwd.jsp").forward(request, response);
		}

	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void updInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		String userName = request.getParameter("userName");
		String comm = request.getParameter("comm");
		User user = (User) request.getSession().getAttribute("user");
		user.setUserName(userName);
		user.setComm(comm);
		userService.update(user);
		
		request.getSession().setAttribute("user", user);
		
		response.sendRedirect("/stuscore/");
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
